package com.kds.smarthome.security.jwt;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kds.smarthome.common.AjaxResponse;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 用户未通过身份验证时启动认证流程，通常是通过向客户端返回适当的 HTTP 响应（例如，未授权状态码 401）来触发身份验证。
     * @param request
     * @param response
     * @param authException
     * @throws IOException
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                        AuthenticationException authException) throws IOException {

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        AjaxResponse<?> errorResponse = AjaxResponse.error("未授权的访问");
        response.getWriter().write(objectMapper.writeValueAsString(errorResponse));
    }
}
